<?php

namespace App\Http\Controllers\Bus;

use App\Http\Controllers\Controller;
use App\Http\Controllers\HelperController;
use App\Imports\Bus\BusImport;
use App\Models\Bus\Bus;
use App\Models\Bus\BusDistribution;
use App\Models\Bus\BusQualificationFile;
use App\Models\Dict;
use App\User;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Maatwebsite\Excel\Facades\Excel;

class BusController extends Controller
{
    /**
     * 车辆列表
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function busList(Request $request)
    {
        $params = $countParams = $request->all();
        unset($countParams['pageNumber'], $countParams['pageSize']);
        $data = $this->getBusList($params)->get()->toArray();
        if ($data) {
            $data = $this->transData($data);
        }
        $dataCount = $this->getBusList($countParams)->count();

        return response()->formatJson(['personnel' => $data, 'count' => $dataCount]);
    }

    public function getBusList($params): Builder
    {
        $query = Bus::query()->select(
            'id',
            'license_plate_num',
            'brand',
            'batch',
            'engine_num',
            'frame_nun',
            'old_license_plate_num',
            'issue_at',
            'start_use_at',
            'length',
            'voucher',
            'original',
            'discount',
            'net_worth',
            'model',
            'max_num',
            'type',
            'created_at',
            'is_check',
            'is_scrap'
        );

        if (isset($params['license_plate_num'])) {
            $query->where('license_plate_num', 'like', '%'.$params['license_plate_num'].'%');
        }

        if (isset($params['brand']) && '-1' !== $params['brand']) {
            $query->where('brand', $params['brand']);
        }

        if (isset($params['type']) && '-1' !== $params['type']) {
            $query->where('type', $params['type']);
        }

        if (isset($params['is_scrap']) && '-1' !== $params['is_scrap']) {
            $query->where('is_scrap', $params['is_scrap']);
        }

        if (isset($params['pageNumber'], $params['pageSize'])) {
            $query
                ->limit($params['pageSize'])
                ->offset(($params['pageNumber'] - 1) * $params['pageSize']);
        }

        return $query->orderBy('is_scrap', 'ASC')->orderByDesc('created_at');
    }

    public function transData($data)
    {
        $dict = new Dict();
        $busType = $dict::getOptionsByName('车辆类型');
        $busBrand = $dict::getOptionsByName('车辆品牌');
        $isCheck = $dict::getOptionsByName('是否纳入考核');
        foreach ($data as $key => $bus) {
            foreach ($bus as $filed => $value) {
                if ($filed === 'type') {
                    foreach ($busType as $v) {
                        if ($v['value'] === $value) {
                            $data[$key][$filed] = $v['title'];
                        }
                    }
                }
                if ($filed === 'brand') {
                    foreach ($busBrand as $v) {
                        if ($v['value'] === $value) {
                            $data[$key][$filed] = $v['title'];
                        }
                    }
                }
                if ($filed === 'is_check') {
                    foreach ($isCheck as $v) {
                        if ($v['value'] === $value) {
                            $data[$key][$filed] = $v['title'];
                        }
                    }
                }
            }
        }

        return $data;
    }

    /**
     * 创建车辆信息
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function store(Request $request)
    {
        $params = $request->all();
        if ($params['base']['sign_certificate_url']) {
            $signCertificateUrls = array_column($params['base']['sign_certificate_url'], 'file_path');
            $params['base']['sign_certificate_url'] = implode(',', $signCertificateUrls);
        } else {
            $params['base']['sign_certificate_url'] = '';
        }

        $params['base']['license_plate_num'] = str_replace('陕G', '', $params['base']['license_plate_num']);
        $bus = new Bus($params['base']);
        $result = $bus->save();
        $message = $result ? '添加成功' : '添加失败';

        // 关联资质文件
        if (! empty($params['qualification_file'])) {
            foreach ($params['qualification_file'] as $k => $work) {
                foreach ($work as $v) {
                    $v['type'] = $k;
                    $qualificationFile = new BusQualificationFile($v);
                    $bus->qualificationFile()->save($qualificationFile);
                }
            }
        }

        return response()->formatJson($result, $message);
    }

    /**
     * 获取车辆数据到编辑表单页面
     *
     * @param $id
     *
     * @return mixed
     */
    public function edit($id)
    {
        $bus = Bus::with('qualificationFile')->find($id)->toArray();

        $dataStart = [];
        $dataRegister = [];
        $dataInsurance = [];
        $dataMaintenance = [];
        $dataCylinderAnnualInspection = [];
        $dataTechnicalAssessment = [];

        $signCertificateUrl = explode(',', $bus['sign_certificate_url']);
        $signCertificateUrls = [];
        foreach ($signCertificateUrl as $key => $value) {
            $signCertificateUrls[] = [
                'file_path' => $value,
            ];
        }
        $bus['sign_certificate_url'] = $signCertificateUrls;

        $users = User::all();
        if (optional($bus['qualification_file'])) {
            foreach ($bus['qualification_file'] as $file) {
                $file['user_name'] = $users->where('id', $file['user_id'])->first()->name;
                switch ($file['type']) {
                    case 'start':
                        $dataStart[] = $file;
                        break;
                    case 'register':
                        $dataRegister[] = $file;
                        break;
                    case 'insurance':
                        $dataInsurance[] = $file;
                        break;
                    case 'maintenance':
                        $dataMaintenance[] = $file;
                        break;
                    case 'gus':
                        $dataCylinderAnnualInspection[] = $file;
                        break;
                    case 'technical':
                        $dataTechnicalAssessment[] = $file;
                        break;
                    default:
                }
            }
        }
        $data = [
            'base'               => $bus,
            'qualification_file' => [
                'start'       => $dataStart,
                'register'    => $dataRegister,
                'insurance'   => $dataInsurance,
                'maintenance' => $dataMaintenance,
                'gus'         => $dataCylinderAnnualInspection,
                'technical'   => $dataTechnicalAssessment,
            ],
        ];

        return response()->formatJson($data);
    }

    /**
     * 修改车辆信息
     *
     * @param  Request  $request
     * @param           $id
     *
     * @return mixed
     */
    public function update(Request $request, $id)
    {
        $params = $request->all();
        $bus = Bus::query()->find($id);
        $signCertificateUrls = array_column($params['base']['sign_certificate_url'], 'file_path');
        $params['base']['sign_certificate_url'] = implode(',', $signCertificateUrls);

        $params['base']['license_plate_num'] = str_replace('陕G', '', $params['base']['license_plate_num']);
        $params['base']['old_license_plate_num'] = str_replace('陕G', '', $params['base']['old_license_plate_num']);
        $result = $bus->update($params['base']);
        $message = $result ? '修改成功' : '修改失败';

        // 关联资质文件
        if (! empty($params['qualification_file'])) {
            foreach ($params['qualification_file'] as $k => $work) {
                foreach ($work as $v) {
                    if (! array_key_exists('type', $v)) {
                        $v['type'] = $k;
                        $qualificationFile = new BusQualificationFile($v);
                        $bus->qualificationFile()->save($qualificationFile);
                    }
                }
            }
        }

        return response()->formatJson($result, $message);
    }

    /**
     * 删除车辆信息
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function destroy(Request $request)
    {
        $result = false;
        if ($request->has('ids')) {
            $ids = explode(',', $request['ids']);
            $delCount = Bus::destroy($ids);
            $result = $delCount !== 0;
        }

        $message = $result ? '删除成功' : '删除失败';

        return response()->formatJson($result, $message);
    }

    /**
     * 获取车牌号数组
     *
     * @return mixed
     */
    public function getLicensePlateNumList()
    {
        return response()->formatJson(Bus::query()->pluck('license_plate_num')->toArray());
    }

    public function getLineLicensePlateNum()
    {
        $distributions = BusDistribution::query()
            ->where('end_date', '2030-12-31')
            ->orderBy('line')
            ->orderBy('license_plate_num')
            ->get()
            ->groupBy('line')
            ->toArray();

        $tree = [];
        foreach ($distributions as $k => $v) {
            $line = [];
            $line['title'] = $k !== 0 ? $k.'路' : '停运';
            $line['expand'] = false;
            $children = [];
            foreach ($v as $vv) {
                $child = [];
                $child['title'] = $vv['license_plate_num'];
                $child['expand'] = false;
                $child['license_plate_num'] = $vv['license_plate_num'];
                $children[] = $child;
            }
            $line['children'] = $children;
            $tree[] = $line;
        }

        return response()->formatJson($tree);
    }

    /**
     * 导入现金收入
     *
     * @param  Request  $request
     *
     * @return mixed
     * @throws \Exception
     */
    public function importBus(Request $request)
    {
        $urlParse = parse_url($request->input('url'));
        $excelData = Excel::toArray(new BusImport, public_path().$urlParse['path']);
        $fullData = $excelData[0];

        array_shift($fullData);
        array_shift($fullData);

        $data = [];
        $fields = [
            'index',
            'batch',
            'brand',
            'model',
            'engine_num',
            'frame_nun',
            'license_plate_num',
            'original',
            'discount',
            'net_worth',
            'old_license_plate_num',
            'issue_at',
            'max_num',
            'start_use_at',
            'length',
            'voucher',
            'type',
            'note',
        ];
        $model = [
            '东风牌',
            '亚星牌',
            '宇通牌',
            '中通牌',
        ];
        $type = [
            '燃气车',
            '纯电动',
        ];
        // 整理数据，填充合并的单元格数据
        foreach ($fullData as $k => $row) {
            if ($row[1] === null) {
                $fullData[$k][1] = $fullData[$k - 1][1];
            }
        }
        foreach ($fullData as $k => $row) {
            $item = [];
            foreach ($fields as $index => $field) {
                $item[$field] = $row[$index];
            }
            $item['batch'] = str_replace("\n", ' ', $item['batch']);
            if ($item['original']) {
                $original = explode('+', str_replace('=', '', $item['original']));
                if (count($original) === 2) {
                    $item['original'] = $original[0] + $original[1];
                } else {
                    $item['original'] = $original[0];
                }
            }
            unset($item['index']);
            $item['net_worth'] = $item['original'] - $item['discount'];
            $item['created_at'] = date('Y-m-d H:i:s');
            if ($item['license_plate_num']) {
                $item['license_plate_num'] = Str::of($item['license_plate_num'])->replace('陕G', '');
            }
            if ($item['old_license_plate_num']) {
                $item['old_license_plate_num'] = Str::of($item['license_plate_num'])->replace('陕G', '');
            }
            $item['brand'] = array_search($item['brand'], $model, true);
            $item['type'] = array_search($item['type'], $type, true);
            if ($item['issue_at'] && is_int($item['issue_at'])) {
                $item['issue_at'] = HelperController::transformDateTime($item['issue_at']);
            }
            if ($item['start_use_at'] && is_int($item['start_use_at'])) {
                $item['start_use_at'] = HelperController::transformDateTime($item['start_use_at']);
            }
            $item['created_at'] = date('Y-m-d H:i:s');

            $data[] = $item;
        }

        return response()->formatJson(Bus::query()->insert($data), '导入成功');
    }
}
